﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
using System.IO;

namespace GeneralAdaptiveFramework
{
    public class ClassLoader
    {
        public static Component getInstance(String filePath)
        {
            try
            {
                /* Load in the assembly. */
                Assembly moduleAssembly = Assembly.LoadFile(filePath);

                /* Get the types of classes that are in this assembly. */
                Type[] types = moduleAssembly.GetTypes();

                /* Loop through the types in the assembly until we find
                 * a class that implements a ModuleNamespace.
                 */
                foreach (Type type in types)
                {
                    if (type.Name == "Component")
                    {
                        /* Create a new instance of the 'ModuleNamespace'. */
                        //Component c = (Component)FormatterServices.GetUninitializedObject(typeof(Component));
                        Component c = (Component)Activator.CreateInstance(type);
                        return c;
                    }
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    if (exSub is FileNotFoundException)
                    {
                        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();
                //Display or log the error based on your application.
            }
            return null;
        }
    }
}
